<template>
  <view class="container">
    <view class="order-relet-content">
      <summary-info title="租赁信息" :summaryList="summaryLease" :defaultFold="false">
        <template #leasePeriod>
          <view class="lease-period">
            <view class="lease-period-val">{{
              orderInfo.expectedUseCarTime ? `${orderInfo.expectedUseCarTime} - ${orderInfo.expectedReturnCarTime}` : '-'
            }}</view>
            <view class="lease-period-rentdays" v-if="orderInfo.leaseNumberStr">租期：{{ orderInfo.leaseNumberStr }}</view>
          </view>
        </template>
      </summary-info>
      <summary-info title="客户信息" :summaryList="summaryMember" :defaultFold="false">
        <template #memberName>
          <view class="member-name">
            <template v-if="orderDetailGetted">
              <view class="member-name">{{ orderInfo.memberName }}</view>
              <ve-button
                size="mini"
                type="plain"
                style="margin-left: 10px"
                v-if="orderDetailGetted && (!memberInfo.driverFrontFileId || !memberInfo.driverReverseFileId)"
                @click="uploadDriverLicenseFn"
              >
                未上传驾驶证
              </ve-button>
            </template>
            <template v-else>-</template>
          </view>
        </template>
        <template #cardTypeName>
          <view class="member-name">
            <template v-if="orderDetailGetted">
              <view class="member-name">{{ memberInfo.cardTypeName }}</view>
              <ve-button
                size="mini"
                type="plain"
                style="margin-left: 10px"
                v-if="orderDetailGetted && (!memberInfo.idCardFrontFileId || (memberInfo.cardType == 0 && !memberInfo.idCardReverseFileId))"
                @click="uploadIdCardFn"
              >
                未上传身份证明
              </ve-button>
            </template>
            <template v-else>-</template>
          </view>
        </template>
      </summary-info>

      <ve-form :model="form" :rules="rules" ref="formRef">
        <!-- <contract-card :showFold="true" :defaultFold="false" /> -->
        <ve-card title="交车信息" :class="[!giveCarInfoFold ? 'give-car-info-folded' : '']" fold v-model:initFold="giveCarInfoFold">
          <box-info :carId="orderInfo.carId"></box-info>
          <template #forever-show="{ contentIsShow }">
            <ve-form-item required prop="giveStaffId" label="交车人">
              {{ form.giveStaffName }}
            </ve-form-item>
            <ve-form-item required prop="useStartTime" :borderBottom="contentIsShow" label="交车时间">
              <ve-date-picker v-model="form.useStartTime" mode="datetime" />
            </ve-form-item>
            <ve-form-item label="出库里程" unit="公里">
              {{ outCarMileage }}
            </ve-form-item>
            <ve-form-item label="出库油(电)量">
              {{ outCarOil }}
            </ve-form-item>
          </template>
          <ve-form-item label="交车里程" unit="公里" required prop="giveCarMileage">
            <ve-input-number :precision="0" v-model="form.giveCarMileage" />
          </ve-form-item>
          <ve-form-item label="交车油(电)量" required prop="giveFuelNum">
            <ve-input-number :precision="0" :min="1" :max="99999" v-model="form.giveFuelNum" />
          </ve-form-item>
          <ve-form-item label="交车照片" labelPosition="top">
            <ve-upload v-model="form.giveFileIds" />
          </ve-form-item>
          <ve-form-item label="交车视频" labelPosition="top">
            <ve-upload-video v-model="form.giveVideoFileIds" :readonly="false" />
          </ve-form-item>
          <ve-form-item label="交车备注" :borderBottom="false" labelPosition="top">
            <ve-input type="textarea" v-model="form.useStartRemark" :maxlength="100" />
          </ve-form-item>
        </ve-card>
      </ve-form>
      <!-- 费用信息 -->
      <view class="fee-pane-content">
        <ve-form :model="feeForm" ref="feeFormRef" layout="vertical">
          <ve-card title="交车费用" fold :defaultFold="false">
            <template v-for="(item, index) in feeForm.orderFee" :key="index">
              <fee-pane :orderFeeIndex="index" :inlineCard="true" :disabledOnlineFee="true" />
            </template>
          </ve-card>
        </ve-form>
      </view>
    </view>
    <footer-box id="footer-box">
      <template #extra>
        <feeStatistic />
      </template>
      <ve-button type="primary" :loading="okLoading" size="long" @click="submitFn">完成交车</ve-button>
    </footer-box>
  </view>
</template>
<script setup name="ShortOrderReletOrder">
  import { ref, provide, computed } from 'vue'
  import { getOrdrDetailsAPI } from '@/api/order/lOrder'
  import { finishGiveCarAPI } from '@/api/order/workOrder'
  import summaryInfo from './components/summary-info.vue'
  import boxInfo from '../shortOrder/components/box-info.vue'
  import feePane from './components/order-fee/fee-pane.vue'
  import footerBox from './form/components/footerBox.vue'
  import feeStatistic from './components/order-fee/fee-statistic.vue'
  import { buildCostInfoParam, initFeeDetail, getStoreTemplateDetail } from './components/order-fee/fee-utils.js'
  import useFormFold from '@/hooks/useFormFold'
  import dayjs from 'dayjs'
  import { onLoad, onUnload } from '@dcloudio/uni-app'
  import { getUserInfo } from './tools'
  import { serializeUrlParams } from '@/utils'
  const { foldValidate } = useFormFold([])
  import useToast from '@/hooks/useToast'
  const giveCarInfoFold = ref(true)
  import contractCard from './components/contract/contract-card.vue'
  import { handleContracList } from './tools'

  const form = ref({})
  const orderInfo = ref({})
  const otherParams = ref({})
  const memberInfo = ref({})
  const orderDetailGetted = ref(false)
  const orderId = ref()
  const workId = ref()
  const outCarMileage = ref()
  const outCarOil = ref()
  const defaultStaffId = ref()
  const defaultStaffName = ref()
  onLoad((options) => {
    console.log(options)
    orderId.value = options.id
    workId.value = options.workId
    form.value = {
      id: orderId.value,
      useStartTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    }
    otherParams.value = JSON.parse(options.otherParam)
    form.value.giveStaffId = otherParams.value.giveStaffId //工单负责人id
    form.value.giveStaffName = otherParams.value.giveStaffName //工单负责人name
    outCarMileage.value = otherParams.value.outCarMileage // 出库里程
    outCarOil.value = otherParams.value.outCarOil // 出库油电量
    // 获取订单详情
    getOrdrDetailsAPI({ id: orderId.value }).then((res) => {
      const result = res.result
      orderInfo.value = result.orderInfo
      memberInfo.value = result.memberInfoDto
      orderDetailGetted.value = true
      // 车务专员 | 当前登录者 id
      handleDefaultStaff()
      // 合同信息
      let contractList = handleContracList(orderInfo.value.contractList || [])
      form.value.contractList = contractList

      // 读取门店模板配置
      getStoreTemplateDetail(orderInfo.value.siteId, 2, (storeTemplate, templateId) => {
        let feeValue = feeForm.value
        initFeeDetail(feeValue, storeTemplate)
        // 更新费用模板 id
        priceTemplateId.value = templateId
      })
    })
  })
  const rules = computed(() => {
    let _rule = {
      giveStaffId: [{ required: true, message: '请选择交车人' }],
      useStartTime: [{ required: true, message: '请选择交车时间' }],
      giveCarMileage: [{ required: true, message: '请输入交车里程' }],
      giveFuelNum: [{ required: true, message: '请输入交车油(电)量' }],
    }
    let formValue = form.value
    if (formValue.contractList) {
      formValue.contractList.forEach((contract, index) => {
        if (contract.fileId) {
          _rule[`contractList.${index}.contractNo`] = [{ required: true, message: '请输入合同编号' }]
        }
      })
    }
    return _rule
  })

  const formRef = ref()
  provide('form', form)

  // 顶部统计信息
  const summaryLease = computed(() => {
    const orderInfoVal = orderInfo.value
    return [
      { label: '预计租赁周期', slotName: 'leasePeriod' },
      { label: '交车车牌号', value: orderInfoVal.licenseNo },
      { label: '订单获取方式', value: orderInfoVal.orderAcquisitionTypeName },
      { label: '预订车型', value: orderInfoVal.originalSiteModelName },
      { label: '交车车型', value: orderInfoVal.modelName },
    ]
  })
  const summaryMember = computed(() => {
    const memberInfoVal = memberInfo.value
    const orderInfoVal = orderInfo.value
    let tempList = []
    if (orderInfoVal.clientId) {
      tempList = [
        { label: '承租人', slotName: 'memberName' },
        { label: '企业名称', value: orderInfoVal.clientName },
        { label: '证件类型', slotName: 'cardTypeName' },
      ]
    } else {
      tempList = [
        { label: '承租人', slotName: 'memberName' },
        { label: '证件类型', slotName: 'cardTypeName' },
      ]
    }
    tempList.push(
      ...[
        { label: '联系电话', value: memberInfoVal.phone },
        { label: '证件号', value: memberInfoVal.cardNumber },
      ],
    )
    return tempList
  })

  // 上传驾驶证点击
  const uploadDriverLicenseFn = () => {
    let url = '/pages/order/upload-driver-license?'
    let urlParams = {
      memberId: memberInfo.value.id,
      driverFrontFileId: memberInfo.value.driverFrontFileId,
      driverReverseFileId: memberInfo.value.driverReverseFileId,
      autoUpload: true,
    }
    url += serializeUrlParams(urlParams)
    uni.navigateTo({ url: url })
  }

  // 上传身份证明点击
  const uploadIdCardFn = () => {
    let url = '/pages/order/upload-id-card?'
    let urlParams = {
      memberId: memberInfo.value.id,
      cardType: memberInfo.value.cardType,
      idCardFrontFileId: memberInfo.value.idCardFrontFileId,
      idCardReverseFileId: memberInfo.value.idCardReverseFileId,
      autoUpload: true,
    }
    url += serializeUrlParams(urlParams)
    uni.navigateTo({ url: url })
  }
  // 处理员工默认值
  const handleDefaultStaff = () => {
    new Promise((resolve) => {
      if (orderInfo.value.giveStaffId) {
        resolve({
          employeeId: orderInfo.value.giveStaffId,
          employeeName: orderInfo.value.giveStaffName,
        })
      } else {
        getUserInfo().then((res) => {
          resolve(res)
        })
      }
    }).then(({ employeeId, employeeName }) => {
      defaultStaffId.value = employeeId
      defaultStaffName.value = employeeName
      // 默认交车人
      form.value.giveStaffId = defaultStaffId.value
      form.value.giveStaffName = defaultStaffName.value
    })
  }
  const priceTemplateId = ref()
  const feeFormRef = ref()
  const feeForm = ref({
    randomKey: 0,
    orderFee: [
      {
        // 费用类型（线上费用|线下费用）
        feeType: 1,
        feeDetailList: [],
        priceTemplateId: priceTemplateId,
        feeDetailTypeList: ['addServiceFee', 'preferentialFee', 'otherFee'],
      },
    ],
  })
  provide('feeForm', feeForm)

  const okLoading = ref(false)
  const submitFn = () => {
    formRef.value.validate((valid, errors) => {
      if (valid) {
        let feeFormValue = feeForm.value
        let costInfo = buildCostInfoParam(feeFormValue)
        const param = {
          ...form.value,
          orderFee: costInfo.orderFee[0],
        }
        param.id = workId.value
        okLoading.value = true
        finishGiveCarAPI(param)
          .then(() => {
            useToast({
              title: '完成交车',
            }).then(() => {
              uni.$emit('operateSuccess', 'give-car')
              uni.navigateBack({
                delta: 1,
              })
            })
          })
          .catch(() => {
            okLoading.value = false
          })
      } else {
        foldValidate(errors, true)
      }
    })
  }

  onLoad(() => {
    // 车型选择完成
    uni.$on('uploadDriverLicenseOk', (option) => {
      const { driverFrontFileId, driverReverseFileId } = option
      // 更新驾驶证正反面 id
      memberInfo.value.driverFrontFileId = driverFrontFileId
      memberInfo.value.driverReverseFileId = driverReverseFileId
    })
    uni.$on('uploadIdCardOk', (option) => {
      const { idCardFrontFileId, idCardReverseFileId, cardType } = option
      // 更新身份证明正反面 id
      memberInfo.value.idCardFrontFileId = idCardFrontFileId
      memberInfo.value.idCardReverseFileId = idCardReverseFileId
      // 更新证件类型
      memberInfo.value.cardType = cardType
      memberInfo.value.cardTypeName = cardType == 0 ? '身份证' : '护照'
    })
  })
  onUnload(() => {
    uni.$off('uploadDriverLicenseOk')
    uni.$off('uploadIdCardOk')
  })
</script>
<style lang="less" scoped>
  .container {
    min-height: 100vh;
    display: flex;
    flex-direction: column;
    .order-relet-content {
      padding: 24rpx;
      padding-bottom: 254rpx;
    }
  }
  .lease-period-rentdays {
    font-size: 30rpx;
    color: #3072f6;
    margin-top: 8rpx;
  }
  .rent-days {
    font-size: 30rpx;
    text-align: right;
    color: #3072f6;
  }
  .member-name {
    display: flex;
    align-items: flex-start;
    .ve-button {
      // width: 200rpx;
      position: relative;
      height: 56rpx;
      margin-left: 6rpx;
      margin-top: -8rpx;
      padding: 0 16rpx;
    }
  }

  .fee-pane-content {
    /deep/ .ve-card-content {
      padding-bottom: 0;
    }
  }

  #footer-box {
    height: 250rpx;
    position: fixed;
    bottom: 0;
    background-color: #ffffff;
    z-index: 100;
  }
  .give-car-info-folded {
    /deep/ .ve-card-content {
      padding-bottom: 0;
    }
  }
  .member-name {
    flex: 1;
  }
</style>
